package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.RedisLock;
import com.hmdp.utils.UserHolder;
import org.redisson.RedissonLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedissonClient redissonClient;
    /**
     * 秒杀优惠卷
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        //1.查询优惠卷
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //2.判断秒杀是否开始，是否结束
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始!");
        }
        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已结束!");
        }
        //3.判断库存是否充足
        if(voucher.getStock()<=0){
            return Result.fail("优惠券库存不足!");
        }

        Long userId = UserHolder.getUser().getId();
//        //将锁加在函数调用处，实现事务提交后在解锁的效果
//        synchronized (userId.toString().intern()){     //Long型的toString 方法底层是new的String，
//                                                                                 // 即使下次来的用户相同，但对象还是会发生改变，需要用到intern
//            //获取代理对象（事务）
//            IVoucherOrderService proxy=(IVoucherOrderService) AopContext.currentProxy(); //获取代理对象
//             return proxy.createVoucherOrder(voucherId);   //不使用代理对象调用的话，这个createVoucherOrder就是由this对象调用，并不是Spring给与的代理对象调用，没有事务功能
//        }
        //Redis锁解决集群锁失效问题
        //创建锁对象
        //RedisLock lock = new RedisLock("order:" + userId,stringRedisTemplate);
        RLock lock=redissonClient.getLock("lock:order:"+userId);
        //获取锁
        //可以加入参数，三个参数为获取锁的最大等待时间（期间会重试），锁自动释放时间，时间单位
        boolean hasLock = lock.tryLock();
        if(!hasLock){
            //获取锁失败: return fail 或者 retry 这里业务要求是返回失败
            return Result.fail("请勿重复下单!");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();//获得代理对象
            return proxy.createVoucherOrder(voucherId);//默认是this,我们要实现事务需要proxy
        } catch (IllegalStateException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    @Transactional                        //@Transactional 只对public 方法生效
    public  Result createVoucherOrder(Long voucherId) {
        //一人一单
        Long userId = UserHolder.getUser().getId();
        //查询订单
        int count =query().eq("user_id",userId).eq("voucher_id", voucherId).count();
        //数量大于0，说明已下过单
        if (count>0){
            //不允许下单
            return Result.fail("用户已经购买过一次");
        }
        //4.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock -1")
                .eq("voucher_id", voucherId)
                //.eq("stock",voucher.getStock())//where id = ? and stock =? 添加了乐观锁
                .gt("stock",0)         //where id = ? and stock >0 添加了乐观锁
                .update();
        //5.创建订单
        if(!success){
            return Result.fail("优惠券库存不足!");
        }

        //6.返回订单id
        VoucherOrder voucherOrder = new VoucherOrder();
        //6.1订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        //6.2用户id

        voucherOrder.setUserId(userId);
        //6.3代金券id
        voucherOrder.setVoucherId(voucherId);

        //7.订单写入数据库
        save(voucherOrder);

        //8.返回订单Id
        return Result.ok(orderId);
    }
}
